package com.easy.stock.spider.html;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jboss.netty.handler.codec.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import com.easy.stock.dao.StockInfoDailyDao;
import com.easy.stock.dao.StockInfoDao;
import com.easy.stock.domain.StockInfo;
import com.easy.stock.spider.HttpResponseHandler;
import com.easy.stock.spider.SpiderTask;
import com.easy.stock.spider.SpiderTask.STATUS;

public class SinaStockInfoSpider extends BaseHtmlSpider {
	
	@Autowired
	private StockInfoDao stockInfoDao;
	
	@Autowired
	private StockInfoDailyDao stockInfoDailyDao;
	
	private String baseUrl;
	private int pageSize;
	
	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}
	
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	
	@Override
	protected List<SpiderTask> prepareSeeds() {
		SpiderTask task = new SpiderTask(baseUrl, new SinaStockInfoHandler(this, true), STATUS.READY);
		List<SpiderTask> seeds = new ArrayList<SpiderTask>();
		seeds.add(task);
		return seeds;
	}

	public static class SinaStockInfoHandler extends HttpResponseHandler {
		
		private boolean isRoot;
		
		public SinaStockInfoHandler(BaseHtmlSpider spider, boolean isRoot) {
			super.spider = spider;
			this.isRoot = isRoot;
		}
		
		@Override
		public List<SpiderTask> doOnCompleted(HttpResponse response) throws IOException {
			String content = response.getContent().toString(Charset.forName("GBK"));
			int start = content.indexOf("{");
			int end = content.lastIndexOf("}");
			JSONObject dataObj = new JSONObject(content.substring(start, end+1));
			SinaStockInfoSpider mySpider = (SinaStockInfoSpider)spider;
		
			int totalStockNum = dataObj.getInt("count");
			JSONArray items = dataObj.getJSONArray("data");
			int itemNum = items.length();
			
			Date time = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
			String ts = sdf.format(time);
			sdf = new SimpleDateFormat("yyyyMMdd");
			String dateStr = sdf.format(time);
			
			for(int i=0; i<itemNum; i++) {
				JSONObject item = items.getJSONObject(i);
				StockInfo info = new StockInfo();
				
				info.setId(item.getString("symbol"));
				info.setCnName(item.getString("cname"));
				info.setName(item.getString("name"));
				info.setCurrent(item.getString("price"));
				info.setChange(item.getString("diff"));
				info.setPercent(item.getString("chg"));
				info.setPreclose(item.getString("preclose"));
				info.setOpen(item.getString("open"));
				info.setLow(item.getString("low"));
				info.setHigh(item.getString("high"));
				info.setPettm(item.get("pe").toString());
				info.setMarketCaptital(item.getString("mktcap"));
				info.setVolume(item.getString("volume"));
				info.setCategory(item.get("category_id").toString());
				info.setMarket(item.getString("market"));
				info.setDate(dateStr);
				info.setLastUpdate(ts);
				
				mySpider.stockInfoDao.addStockInfo(info);
				
				// 修改ID, 存储成每日信息
				info.setId(info.getId()+"-"+info.getDate());
				mySpider.stockInfoDailyDao.addStockInfo(info);
			}
			
			if(isRoot) {
				int otherPages = totalStockNum/mySpider.pageSize+1;
				// 跳过第一页
				List<SpiderTask> otherTasks = new ArrayList<SpiderTask>();
				for(int i=2; i<=otherPages; i++) {
					SpiderTask otherTask = new SpiderTask(
							mySpider.baseUrl+"&page="+i,
							new SinaStockInfoHandler(mySpider, false),
							STATUS.READY);
					
					otherTasks.add(otherTask);
				}
				
				System.out.println("tasknum="+otherTasks.size());
				return otherTasks;
			}

			return null;
		}
		
		@Override
		public void doOnThrowable(Throwable t) {
			// DO nothing
		}
	}
}
